/**
 * 作者:hanbo
 * 日期:2019/1/3016:16
 * 描述:
 */

let selection = {};

/**
 * 开始框选监听
 */
function startSelection() {
    selection.points = [];
    selection.click = function (e) {
        switch (selection.points.length) {
            case 0:
                selection.points.push(e.latlng);
                break;
            case 1:
                selection.points.push(e.latlng);
                drawRectangle(selection.points, "selection");
                setDownBtnState(true);
                break;
            case 2:
                selection.points = [];
                setDownBtnState(false);
                removeLayer("selection");
                selection.points.push(e.latlng);
                break;
            default:
                break;
        }
    };
    selection.mousemove = function (e) {
        if (selection.points.length == 1) {
            removeLayer("selection");
            drawRectangle([selection.points[0], e.latlng], "selection");
        }
    };
    map.on("click", selection.click);
    map.on("mousemove", selection.mousemove);
}

/**
 * 关闭框选监听
 */
function endSelection() {
    map.off("click mousemove");
    selection = {};
    setDownBtnState(false);
    removeLayer("selection")
}

/**
 * 开始下载瓦片
 */
function downTiles() {
    let levelMin = Number($("input.minSelector").val());
    let levelMax = Number($("input.maxSelector").val());
    closeLevelSelector();
    let point1 = selection.points[0];
    point1 = Wgs84ToMector2(point1.lat, point1.lng);
    let point2 = selection.points[1];
    point2 = Wgs84ToMector2(point2.lat, point2.lng);
    showProgress();
    setPercentage("0", "开始计算");
    let coordinates = [];
    for (let i = levelMin; i <= levelMax; i++) {
        let tmp = getTMSCoord(Math.min(point1[0], point2[0]), Math.min(point1[1], point2[1]), Math.max(point1[0], point2[0]), Math.max(point1[1], point2[1]), i, 0);
        if(tmp.length==0){
            coordinates=[];
            break;
        }else {
            coordinates = coordinates.concat(tmp);
        }
    }
    totalNumber=coordinates.length;
    if(totalNumber==0){
       sendError("下载失败", "选择范围过大，存在内存泄漏风险");
        hideProgress();
    }else {
        setPercentage("0", "计算完成，共" + coordinates.length + "个切片");
        sendDownCmd(coordinates);
    }
}

/**
 * 设置下载按钮状态
 * @param bool {Boolean}
 */
function setDownBtnState(bool) {
    menu.getMenuItemById("down").enabled = bool;
}